package com.jiangnan.ui.activity

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.jiangnan.R
import com.jiangnan.databinding.ActivityForgetPasswordBinding
import com.jiangnan.util.ToastUtil
import com.jiangnan.viewmodel.AuthViewModel

class ForgetPasswordActivity : BaseActivity(), View.OnClickListener, TextWatcher {

    private lateinit var binding: ActivityForgetPasswordBinding
    private lateinit var viewModel: AuthViewModel

    // 定义正则表达式
    private val phoneRegex = Regex("^1[3-9]\\d{9}$")
    // 密码正则：仅允许数字、英文大小写、下划线、减号和@，长度6-20
    private val passwordRegex = Regex("^(?=.{6,20}$)[0-9A-Za-z_\\-@]+$")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_forget_password)
        binding.lifecycleOwner = this

        viewModel = ViewModelProvider(this).get(AuthViewModel::class.java)
        binding.viewModel = viewModel

        binding.sendCodeButton.setOnClickListener(this)
        binding.resetPasswordButton.setOnClickListener(this)
        binding.phoneInput.addTextChangedListener(this)
        binding.newPasswordInput.addTextChangedListener(this)
        binding.confirmPasswordInput.addTextChangedListener(this)
        binding.codeInput.addTextChangedListener(this)

        initObserve()

        toastMessage()
    }

    private fun initObserve() {
        // 观察发送验证码结果（此处可根据需求设置提示）
        viewModel.smsResponse.observe(this) { res ->
            res?.let {
                if (it.code == 1) {
                    binding.codeInput.error = null
                    // 如需要可显示倒计时或其他提示
                } else {
                    binding.phoneInput.error = it.msg
                }
            }
        }

        // 观察重置密码接口返回结果
        viewModel.resetResponse.observe(this) { res ->
            res?.let {
                if (it.code == 1) {
                    // 重置密码成功，提示用户或跳转到登录界面
                    // 例如：Toast.makeText(this, "密码重置成功", Toast.LENGTH_SHORT).show()
                } else {
                    // 错误提示，可以在某个 TextView 显示错误信息
                    binding.newPasswordInput.error = it.msg
                }
            }
        }
    }

    private fun toastMessage() {
        viewModel.toastMessage.observe(this) { event ->
            event.getContentIfNotHandled()?.let { message ->
                ToastUtil.showShort(this, message)
            }
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.send_code_button -> {
                // 发送验证码时仅校验手机号
                val phone = binding.phoneInput.text.toString().trim()
                if (phone.isEmpty()) {
                    binding.phoneInput.error = "请输入手机号"
                    return
                }
                if (!phoneRegex.matches(phone)) {
                    binding.phoneInput.error = "请输入有效的手机号"
                    return
                }
                binding.phoneInput.error = null
                // 调用 ViewModel 发送验证码
                viewModel.sendSmsCode(phone)
            }
            R.id.reset_password_button -> {
                // 重置密码时需要校验所有输入项
                val phone = binding.phoneInput.text.toString().trim()
                val code = binding.codeInput.text.toString().trim()
                val newPassword = binding.newPasswordInput.text.toString().trim()
                val confirmPassword = binding.confirmPasswordInput.text.toString().trim()

                var valid = true

                if (phone.isEmpty()) {
                    binding.phoneInput.error = "请输入手机号"
                    valid = false
                } else if (!phoneRegex.matches(phone)) {
                    binding.phoneInput.error = "请输入有效的手机号"
                    valid = false
                } else {
                    binding.phoneInput.error = null
                }

                if (code.isEmpty()) {
                    binding.codeInput.error = "请输入验证码"
                    valid = false
                } else {
                    binding.codeInput.error = null
                }

                if (newPassword.isEmpty()) {
                    binding.newPasswordInput.error = "请输入新密码"
                    valid = false
                } else if (!passwordRegex.matches(newPassword)) {
                    binding.newPasswordInput.error = "密码只能由数字、英文字符、下划线、减号和@组成,长度为6-20"
                    valid = false
                } else {
                    binding.newPasswordInput.error = null
                }

                if (confirmPassword.isEmpty()) {
                    binding.confirmPasswordInput.error = "请再次输入新密码"
                    valid = false
                } else if (newPassword != confirmPassword) {
                    binding.confirmPasswordInput.error = "两次密码输入不一致"
                    valid = false
                } else {
                    binding.confirmPasswordInput.error = null
                }
                // 检查是否同意协议
                if (!binding.cbAgree.isChecked) {
                    binding.cbAgree.error = "请先同意协议"
                    valid = false
                }else{
                    binding.cbAgree.error = null
                }
                if (!valid) return


                // 所有校验通过后，调用 ViewModel 重置密码
                viewModel.resetPassword(phone, code, newPassword)
            }
        }
    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        // 不需要处理
    }

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        // 不需要处理
    }

    override fun afterTextChanged(s: Editable?) {
        // 可在此处增加实时校验（参考 LoginActivity 的处理方式），此处略
    }
}
